import React from 'react';
import PropTypes from 'prop-types';
import { Layout, Menu, Icon, Avatar, Dropdown, Tag, message, Spin } from 'antd';
import DocumentTitle from 'react-document-title';
import { connect } from 'dva';
import { Link, routerRedux, Route, Redirect, Switch } from 'dva/router';

import moment from 'moment';
import groupBy from 'lodash/groupBy';
import styles from './BasicLayout.less';
import HeaderSearch from '../components/HeaderSearch';
import NoticeIcon from '../components/NoticeIcon';
import GlobalFooter from '../components/GlobalFooter';

import { UserRouter, CommonRouter, AdminRouter } from '../utils/utils';
import Storage from '../utils/localstore';
import { userNav } from '../common/userNav';
import { adminNav } from '../common/adminNav';
// import { sysNav } from '../common/systemNav';

const { Header, Sider, Content } = Layout;
const { SubMenu } = Menu;

@connect(state => ({
  currentUser: state.user.currentUser,
  isLogin: state.user.isLogin,
  notifyCount: state.user.notifyCount,
  collapsed: state.global.collapsed,
  fetchingNotices: state.global.fetchingNotices,
  notices: state.global.notices,
}))
export default class BasicLayout extends React.PureComponent {
  static childContextTypes = {
    location: PropTypes.object,
    breadcrumbNameMap: PropTypes.object,
  }

  constructor(props) {
    super(props);
    this.state = {
      openKeys: this.getDefaultCollapsedSubMenus(props),
      menus: userNav, // default to show user navigation
      router: CommonRouter, // default to common router
    };
  }

  state = {
    menus: userNav, // default to show user navigation
    router: CommonRouter, // default to common router
  }
  // router url
  getChildContext() {
    const { location } = this.props;
    const breadcrumbNameMap = {};
    this.state.router.forEach((item) => {
      breadcrumbNameMap[item.path] = item.name;
    });
    return { location, breadcrumbNameMap };
  }

  componentDidMount() {
    const { isLogin, currentUser } = this.props;

    const uid = Storage.get('uid');
    const token = Storage.get('access_token');

    if (isLogin) {
      return;
    }

    // if not login
    if (!uid && !token) {
      this.props.dispatch(routerRedux.push('/user/login'));
      return;
    }

    // if not user info
    if (uid && token && !currentUser) {
      this.props.dispatch({
        type: 'user/fetchUserProfile',
        payload: { uid },
      });
    }
  }

  componentWillReceiveProps(nextProps) {
    if (!nextProps.currentUser) {
      return;
    }

    try {
      const role = nextProps.currentUser.org_role;
      if (role) {
        const router = [...CommonRouter, ...AdminRouter];
        this.setState({
          menus: adminNav,
          router,
        });
      } else {
        const router = [...CommonRouter, ...UserRouter];
        this.setState({
          menus: userNav,
          router,
        });
      }
    } catch (e) {
      console.log('build router error: ', e);
    }
  }

  componentWillUnmount() {
    clearTimeout(this.resizeTimeout);
  }

  onCollapse = (collapsed) => {
    this.props.dispatch({
      type: 'global/changeLayoutCollapsed',
      payload: collapsed,
    });
  }

  onMenuClick = ({ key }) => {
    if (key === 'logout') {
      this.props.dispatch({ type: 'user/logout' });
      this.props.dispatch({ type: 'login/logout' });
      Storage.remove('uid');
      Storage.remove('access_token');
      this.props.dispatch(routerRedux.push('/user/login'));
    }
  }

  getDefaultCollapsedSubMenus(props) {
    const currentMenuSelectedKeys = [...this.getCurrentMenuSelectedKeys(props)];
    currentMenuSelectedKeys.splice(-1, 1);
    if (currentMenuSelectedKeys.length === 0) {
      return ['dashboard'];
    }
    return currentMenuSelectedKeys;
  }

  getCurrentMenuSelectedKeys = (props) => {
    const { location: { pathname } } = props || this.props;
    const keys = pathname.split('/').slice(1);
    if (keys.length === 1 && keys[0] === '') {
      return [this.state.menus[0].key];
    }
    return keys;
  }

  getNavMenuItems(menusData, parentPath = '') {
    if (!menusData) {
      return [];
    }

    return menusData.map((item) => {
      if (!item.name) {
        return null;
      }
      let itemPath;
      if (item.path.indexOf('http') === 0) {
        itemPath = item.path;
      } else {
        itemPath = `${parentPath}/${item.path || ''}`.replace(/\/+/g, '/');
      }

      if (item.children && item.children.some(child => child.name)) {
        return (
          <SubMenu
            title={
              item.icon ? (
                <span>
                  <Icon type={item.icon} />
                  <span>{item.name}</span>
                </span>
              ) : item.name
            }
            key={item.key || item.path}
          >
            {this.getNavMenuItems(item.children, itemPath)}
          </SubMenu>
        );
      }
      const icon = item.icon && <Icon type={item.icon} />;
      return (
        <Menu.Item key={item.key || item.path}>
          {
            /^https?:\/\//.test(itemPath) ? (
              <a href={itemPath} target={item.target}>
                {icon}<span>{item.name}</span>
              </a>
            ) : (
              <Link to={itemPath} target={item.target}>
                {icon}<span>{item.name}</span>
              </Link>
            )
          }
        </Menu.Item>
      );
    });
  }

  getPageTitle = () => {
    return '企创宝资产管理';
  }

  getNoticeData = () => {
    const notices = [
      {
        id: '000000011',
        title: '新用户注册提醒',
        description: '2017-01-09 又有新用户注册啦',
        extra: '过去一天内已有34新用户注册',
        status: 'doing',
        type: '消息',
      },
    ];

    if (notices.length === 0) {
      return {};
    }
    const newNotices = notices.map((notice) => {
      const newNotice = { ...notice };
      if (newNotice.datetime) {
        newNotice.datetime = moment(notice.datetime).fromNow();
      }
      // transform id to item key
      if (newNotice.id) {
        newNotice.key = newNotice.id;
      }
      if (newNotice.extra && newNotice.status) {
        const color = ({
          todo: '',
          processing: 'blue',
          urgent: 'red',
          doing: 'gold',
        })[newNotice.status];
        newNotice.extra = <Tag color={color}>{newNotice.extra}</Tag>;
      }
      return newNotice;
    });
    return groupBy(newNotices, 'type');
  }

  handleOpenChange = (openKeys) => {
    const latestOpenKey = openKeys.find(key => this.state.openKeys.indexOf(key) === -1);
    this.setState({
      openKeys: latestOpenKey ? [latestOpenKey] : [],
    });
  }

  toggle = () => {
    const { collapsed } = this.props;
    this.props.dispatch({
      type: 'global/changeLayoutCollapsed',
      payload: !collapsed,
    });
    this.resizeTimeout = setTimeout(() => {
      const event = document.createEvent('HTMLEvents');
      event.initEvent('resize', true, false);
      window.dispatchEvent(event);
    }, 600);
  }

  handleNoticeClear = (type) => {
    message.success(`清空了${type}`);
    this.props.dispatch({
      type: 'global/clearNotices',
      payload: type,
    });
  }

  handleNoticeVisibleChange = (visible) => {
    if (visible) {
      this.props.dispatch({
        type: 'global/fetchNotices',
      });
    }
  }

  // render side menu
  renderSideMenu() {
    return this.getNavMenuItems(this.state.menus);
  }

  render() {
    const { currentUser, collapsed, fetchingNotices, notifyCount } = this.props;
    const menu = (
      <Menu className={styles.menu} selectedKeys={[]} onClick={this.onMenuClick}>
        <Menu.Item>
          <Link to="/profile/organ">
            <Icon type="user" />
            个人中心
          </Link>
        </Menu.Item>
        <Menu.Item disabled><Icon type="setting" />设置</Menu.Item>
        <Menu.Divider />
        <Menu.Item key="logout"><Icon type="logout" />退出登录</Menu.Item>
      </Menu>
    );

    const noticeData = this.getNoticeData();

    // Don't show popup menu when it is been collapsed
    const menuProps = collapsed ? {} : {
      openKeys: this.state.openKeys,
    };

    return (
      <DocumentTitle title={this.getPageTitle()}>
        <Layout>
          <Sider
            trigger={null}
            collapsible
            collapsed={collapsed}
            collapsedWidth={80}
            breakpoint="md"
            onCollapse={this.onCollapse}
            width={256}
            className={styles.sider}
          >
            <div className={styles.logo}>
              <Link to="/">
                <img src="https://gw.alipayobjects.com/zos/rmsportal/iwWyPinUoseUxIAeElSx.svg" alt="logo" />
                <h1>QCB Assets Beta</h1>
              </Link>
            </div>
            <Menu
              theme="light"
              mode="inline"
              {...menuProps}
              onOpenChange={this.handleOpenChange}
              selectedKeys={this.getCurrentMenuSelectedKeys()}
              style={{ margin: '16px 0', width: '100%' }}
            >
              {this.renderSideMenu()}
            </Menu>
          </Sider>
          <Layout>
            <Header className={styles.header}>
              <Icon
                className={styles.trigger}
                type={collapsed ? 'menu-unfold' : 'menu-fold'}
                onClick={this.toggle}
              />
              <div className={styles.right}>
                <HeaderSearch
                  className={`${styles.action} ${styles.search}`}
                  placeholder="站内搜索"
                  dataSource={['搜索类型', '搜索今日最新', '随便搜搜']}
                />
                <NoticeIcon
                  className={styles.action}
                  count={notifyCount}
                  onClear={this.handleNoticeClear}
                  onPopupVisibleChange={this.handleNoticeVisibleChange}
                  loading={fetchingNotices}
                  popupAlign={{ offset: [20, -16] }}
                >
                  <NoticeIcon.Tab
                    list={noticeData['通知']}
                    title="通知"
                    emptyText="你已查看所有通知"
                    emptyImage="https://gw.alipayobjects.com/zos/rmsportal/wAhyIChODzsoKIOBHcBk.svg"
                  />
                  <NoticeIcon.Tab
                    list={noticeData['消息']}
                    title="消息"
                    emptyText="您已读完所有消息"
                    emptyImage="https://gw.alipayobjects.com/zos/rmsportal/sAuJeJzSKbUmHfBQRzmZ.svg"
                  />
                  <NoticeIcon.Tab
                    list={noticeData['待办']}
                    title="待办"
                    emptyText="你已完成所有待办"
                    emptyImage="https://gw.alipayobjects.com/zos/rmsportal/HsIsxMZiWKrNUavQUXqx.svg"
                  />
                </NoticeIcon>
                {currentUser && currentUser.contact_email ? (
                  <Dropdown overlay={menu}>
                    <span className={`${styles.action} ${styles.account}`}>
                      <Avatar size="small" className={styles.avatar} src={currentUser.avatar} />
                      {currentUser.contact_email}
                    </span>
                  </Dropdown>
                ) : <Spin size="small" style={{ marginLeft: 8 }} />}
              </div>
            </Header>
            <Content style={{ margin: '24px 24px 0', height: '100%' }}>
              <Switch>
                {this.state.router.map(item => <Route {...item} key={item.keys} />)}
                <Redirect to="/dashboard/analysis" />
              </Switch>
              <GlobalFooter
                copyright={
                  <div>
                    Copyright <Icon type="copyright" /> 2017 企创宝体验技术部出品
                  </div>
                }
              />
            </Content>
          </Layout>
        </Layout>
      </DocumentTitle>
    );
  }
}
